<?php
/**
 * Created by PhpStorm.
 * User: 86188
 * Date: 2021/3/4
 * Time: 10:45
 */

namespace app\admin\controller;


use app\service\apiService;
use app\service\billService;
use app\service\roominfoService;
use app\service\wxtplService;
use think\facade\Db;
use think\facade\View;

class Billcheck extends Common
{
    public function test(){
        $g="/^1[34578]\d{9}$/";
        $mail="";
    }
    public function billlist(){
        //查询小区信息
        $com = $this->pidTokenId();

        $whe['community_id'] = array('in',$com['community_id']);

        $communitylist = (new roominfoService())->communityList($whe);
        View::assign('communitylist',$communitylist);

        $where=array();
        $page = request()->has('page') ? request()->get('page') : 1;

        $billlist =Db::name('bill_check')
            ->where('community_id', 'in', $com['community_id'])
            ->order('id desc')->paginate(20, false, [
                'page'  =>  $page,
                'query' =>  $where
            ]);
        $render=$billlist->render();
        View::assign('render',$render);
        View::assign('list',$billlist);
        if(!empty($billlist)){
            foreach($billlist as $bill){
                //根据小区编号查询小区名称
                $community = (new billService())->communityName($bill['community_id']);
                $bill['community_id'] = $community['community_name'];
                //根据房屋门牌号查询业主信息
                $bill['owner_name'] = (new billService())->billOwnerName($bill['out_room_id']);
                $bill['address'] = Db::name('roominfo')->where('out_room_id',$bill['out_room_id'])->value('address');;
                $bill['costtype'] = Db::name('bill')->where('id',$bill['billid'])->value('cost_type');;
                //数据从新存入数组
                $list[] = $bill;
                View::assign('list',$list);
            }
        }
        return View::fetch();
    }

    //
    public function billadd(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        View::assign('communitylist',$communitylist);
        //查询费用类型

        $type = (new billService())->costtype($com);
        View::assign('type',$type);

        if(request()->isPOST()){
            //获取表单数据
            $data = request()->post();
            $billinfo=Db::table("bill")->where("id",$data["billid"])->find();
            if(empty($billinfo)){
                return "error";
            }
            if(($billinfo["bill_entry_amount"]==$data["bill_entry_amount"])&&($billinfo["acct_period"]==$data["acct_period"])){
                return "error";
            }
            $billcheck["community_id"]=$data["community_id"];
            $billcheck["billid"]=$data["billid"];
            $billcheck["bill_entry_amount"]=$data["bill_entry_amount"];
            $billcheck["acct_period"]=$data["acct_period"];
            $billcheck["out_room_id"]=$billinfo["out_room_id"];
            $billcheck["create_time"]=time();
            $billcheck["username"]=session("name");

            $resid=Db::table("bill_check")->insertGetId($billcheck);
            if($resid){
                $wxuserlist=Db::table("community_wxuser")->where("community_id",$data["community_id"])->select()->toArray();

                foreach ($wxuserlist as $userinfo){
                    $tenpalate_id="OazWbiMUE_-NM70xR6DvVDpMNQlHpZsbEVy_AKmzZbo";
                    $url="https://www.wuye.zfbzhsq.com/index/billcheck/index?id=".$resid;
                    $communityinfo=Db::table("community")->where("community_id",$billinfo["community_id"])->find();
                    $first=$communityinfo["community_name"]."-".$billinfo["room_address"];
                    $keyword1="小区有账单需要修改";
                    $keyword3=session("name");
                    $remark="请尽快帮我审核";
                    $ctime=date("Y-m-d H:i:s");
                    $data=(new wxtplService())->json_tempalte_review($userinfo["openid"],$tenpalate_id,$url,$first,$keyword1,$ctime,$keyword3,$ctime,$remark);
                    $access_token=(new Basewxget())->gettoken();
                    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                    $res=(new wxtplService())->curl_post($url,$data);
                    //Log::write($res,"wxusermsgt");
                }
                return "ok";
            }else{
                return "error";
            }
            //Db::table()->insert();



        }else{
            return View::fetch('billadd');
        }
    }

    public function getdata(){
        $community_id = request()->post('community_id');
        $group = request()->post('group');
        $building = request()->post('building');
        $unit = request()->post('unit');
        $room=request()->post('room');

        $roominfo=Db::table("roominfo")
                ->where("community_id",$community_id)
                ->where("group",$group)
                ->where("building",$building)
                ->where("unit",$unit)
                ->where("room",$room)
                ->find();
        if(empty($roominfo)){
            return "error";
        }
        $billlist=Db::table("bill")
                    ->where("out_room_id",$roominfo["out_room_id"])
                    ->where("status","WAIT_PAYMENT")
                    ->select()->toArray();
        return $billlist;
    }

    public function checksuccess(){
        $id=request()->param("id");

        $info=Db::table("bill_check")->where("id",$id)->find();
        if(empty($info)){
            return "该订单不存在";
        }
        if($info["check_status"]!="2"){
            return "该订单已审核完成";
        }
        View::assign("info",$info);

        $billinfo=Db::table("bill")->where("id",$info["billid"])->find();
        if(empty($billinfo)){
            return "该订单不存在";
        }
        if($billinfo["status"]!="WAIT_PAYMENT"){
            return "该订单已支付，无法审核";
        }

        if($billinfo["tongbu"]=="2"){
            Db::startTrans();
            try{
                //更新账单状态
                Db::table('bill')
                    ->where("id",$info["billid"])
                    ->update([
                            "bill_entry_amount"=>$info["bill_entry_amount"],
                            "acct_period"=>$info["acct_period"]
                        ]
                    );

                Db::table("bill_check")
                    ->where("id",$id)
                    ->update([
                        "check_status"=>1,
                        "check_time"=>time(),
                        "check_openid"=>session("name")
                    ]);
                // 提交事务
                Db::commit();

                //给用户发送账单更新成功通知
                $admininfo=Db::table("admin")->where("name",$info["username"])->find();
                if((!empty($admininfo))&&($admininfo["openid"]!='0')){
                    $openid=$admininfo["openid"];
                    $url="";
                    $first="您的账单修改成功";
                    $keyword1="账单修改";

                    $keyword2="修改成功";
                    $keyword3="";
                    $remark="";
                    $data=(new wxtplService())->json_tempalte_checksuccess($openid,$url,$first,$keyword1,$keyword2,$keyword3,$remark);
                    $access_token=(new Basewxget())->gettoken();
                    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                    $res=(new wxtplService())->curl_post($url,$data);

                }
                return "ok";
            } catch (\Exception $e) {
                // 回滚事务

                Db::rollback();
                return $e->getMessage();
            }

        }elseif($billinfo["tongbu"]=="1"){
            //已上线支付宝

            $token = (new billService())->billinfoToken($info['community_id']);

            $api = new apiService(config('app')['roombilledit'], 'https://openapi.alipay.com/gateway.do');
            $res = $api->roomBillEdit(json_encode(['batch_id' => $billinfo['batch_id'], 'community_id' =>  $billinfo['community_id'], 'bill_entry_id' => $billinfo['bill_entry_id'],'out_room_id' => $billinfo['out_room_id'], 'room_address' => $billinfo['room_address'], 'cost_type' => $billinfo['cost_type'], 'bill_entry_amount' => $info['bill_entry_amount'], 'acct_period' => $info['acct_period'], 'release_day' => $billinfo['release_day'], 'deadline' => $billinfo['deadline'],  'token' => $token]));

            //判断是否存入支付宝
            if (!isset($res['error'])){
                $resu=$res['success'];
                if(isset($resu->alive_bill_entry_list)){
                    return "账单支付中无法修改";
                }
                Db::table('bill')
                    ->where("id",$info["billid"])
                    ->update([
                            "bill_entry_amount"=>$info["bill_entry_amount"],
                            "acct_period"=>$info["acct_period"]
                        ]
                    );

                Db::table("bill_check")
                    ->where("id",$id)
                    ->update([
                        "check_status"=>1,
                        "check_time"=>time(),
                        "check_openid"=>session("name")
                    ]);

                //给用户发送账单更新成功通知
                $admininfo=Db::table("admin")->where("name",$info["username"])->find();
                if((!empty($admininfo))&&($admininfo["openid"]!='0')){
                    $openid=$admininfo["openid"];
                    $url="";
                    $first="您的账单修改成功";
                    $keyword1="账单修改";

                    $keyword2="修改成功";
                    $keyword3="";
                    $remark="";
                    $data=(new wxtplService())->json_tempalte_checksuccess($openid,$url,$first,$keyword1,$keyword2,$keyword3,$remark);
                    $access_token=(new Basewxget())->gettoken();
                    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                    $res=(new wxtplService())->curl_post($url,$data);

                }
                return "ok";

            }else{
                return $res['error'];

            }
        }
    }

    public function checkfail(){
        $id=request()->param("id");
        $info=Db::table("bill_check")->where("id",$id)->find();
        if(empty($info)){
            return "该订单不存在";
        }
        if($info["check_status"]!="2"){
            return "该订单已审核完成";
        }
        $res=Db::table("bill_check")
            ->where("id",$id)
            ->update([
                "check_status"=>3,
                "check_time"=>time(),
                "check_openid"=>session("name")
            ]);
        if($res){
            $admininfo=Db::table("admin")->where("name",$info["username"])->find();
            if((!empty($admininfo))&&($admininfo["openid"]!='0')){
                $openid=$admininfo["openid"];
                $url="";
                $first="您的账单修改信息被驳回";
                $keyword1="审核退回";
                $roominfo=Db::table("roominfo")->where("out_room_id",$info["out_room_id"])->find();
                $communityinfo=Db::table("community")->where("community_id",$info["community_id"])->find();
                $keyword2=$communityinfo["community_name"]."-".$roominfo["address"];
                $remark="";
                $data=(new wxtplService())->json_tempalte_back($openid,$url,$first,$keyword1,$keyword2,$remark);
                $access_token=(new Basewxget())->gettoken();
                $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
                $res=(new wxtplService())->curl_post($url,$data);
                //Log::write($res,"wxusermsg");

            }
            return "ok";
        }else{
            return "该订单审核失败,请重新审核";
        }
    }
}